#include "stdafx.h"
#include "Server.h"

#include <sstream>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace pktoondb
{
	const int Server::REGISTRY_CATEGORY = 1;
	const int Server::DISPATCH_CATEGORY = 2;
	const int Server::RESOURCE_CATEGORY = 3;

	IMPLEMENT_RECORD(Server)

	Server::Server(void)
	{
	}

	Server::~Server(void)
	{
	}

	int Server::GetServerId() const
	{
		return this->GetRawValue<int>("id");
	}

	// static
	Server* Server::FindByServerName(const std::string& serverName)
	{
		std::stringstream condition;
		condition << "`server_name`=\"" << serverName << "\"";
		return Server::FindFirst(condition.str());
	}

	// static
	bool Server::IsServerExist(const std::string& serverName)
	{
		Server* server = Server::FindByServerName(serverName);
		if (server)
		{
			delete server;
			return true;
		}
		else
		{
			return false;
		}
	}

	// static
	int Server::InsertRegistryService(const std::string &serverName)
	{
		FieldMap* fieldmap = new FieldMap;
		fieldmap->insert(std::make_pair("server_name", pktoondb::Any(serverName)));
		fieldmap->insert(std::make_pair("category", pktoondb::Any(REGISTRY_CATEGORY)));
		Server* server = Server::Create(fieldmap);
		int serverId = server->GetServerId();
		delete server;
		return serverId;
	}

	// static
	int Server::InsertDispatchService(const std::string &serverName)
	{
		FieldMap* fieldmap = new FieldMap;
		fieldmap->insert(std::make_pair("server_name", pktoondb::Any(serverName)));
		fieldmap->insert(std::make_pair("category", pktoondb::Any(DISPATCH_CATEGORY)));
		Server* server = Server::Create(fieldmap);
		int serverId = server->GetServerId();
		delete server;
		return serverId;
	}

	// static
	int Server::InsertResourceService(const std::string &serverName)
	{
		FieldMap* fieldmap = new FieldMap;
		fieldmap->insert(std::make_pair("server_name", pktoondb::Any(serverName)));
		fieldmap->insert(std::make_pair("category", pktoondb::Any(RESOURCE_CATEGORY)));
		Server* server = Server::Create(fieldmap);
		int serverId = server->GetServerId();
		delete server;
		return serverId;
	}

	// static
	int Server::CountService(int type)
	{
		std::stringstream conditions;
		conditions << "`category`=" << type;
		return Server::Count("category", conditions.str());
	}

	//static
	int Server::CountRegistryService()
	{
		return Server::CountService(REGISTRY_CATEGORY);
	}

	//static
	int Server::CountDispatchService()
	{
		return Server::CountService(DISPATCH_CATEGORY);
	}

	//static
	int Server::CountResourceService()
	{
		return Server::CountService(RESOURCE_CATEGORY);
	}
}
